package com.kaifamiao.wendao.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听来访人数
 */
@WebListener
public class OnlineCountListener implements HttpSessionListener {

    //创建session监听
    //一旦创建一个session，就会触发一次这个
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        //要想统计session，作用域要提到最高
        ServletContext servletContext = event.getSession().getServletContext();
        System.out.println(event.getSession().getId());
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");

        if (onlineCount==null){
            onlineCount = 1;
        }else {
            int count = onlineCount.intValue();
            onlineCount += 1;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount",onlineCount);
    }

    //销毁session监听
    //一旦session销毁，就会触发

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext servletContext = event.getSession().getServletContext();
        Integer onlineCount =(Integer) servletContext.getAttribute("OnlineCount");

        if (onlineCount==null){
            onlineCount = 0;
        }else {
            int count = onlineCount.intValue();
            onlineCount -= 1;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount",onlineCount);
    }
}
